﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using pdfebookcutter.Properties;
using System.IO;
using Microsoft.VisualBasic.FileIO;

namespace pdfebookcutter
{
    public partial class MDIParent : Form
    {
        public MDIParent()
        {
            InitializeComponent();

       
            Text = AboutBox1.AssemblyTitle;

        }

        private void OpenFile(object sender, EventArgs e)
        {
          
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                foreach(var FileName in openFileDialog1.FileNames)
                    OpenFile(FileName);
            }
        }

        private void OpenFile(string FileName)
        {
            var childForm = new PageForm()
            {
                MdiParent = this,
                Text = FileName
            };
            childForm.LoadFile(FileName);
            childForm.Show();
        }

        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var activeDocument = ActiveMdiChild as PageForm;
            if (activeDocument == null)
                return;

            if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = saveFileDialog1.FileName;
                activeDocument.SaveAs(FileName);
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip.Visible = toolBarToolStripMenuItem.Checked;
        }

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using(var box = new AboutBox1())
                box.ShowDialog();
        }

        public class QueueItem
        {
            public Action Work;
            public Action ProgressAction;
        }

        Queue<QueueItem> Actions = new Queue<QueueItem>();

        public void ScheduleAction(Action WorkAction, Action ProgressAction)
        {
            lock (Actions)
            {
                Actions.Enqueue(new QueueItem() { Work = WorkAction, ProgressAction = ProgressAction });
            }

            toolStripProgressBar1.Maximum++;

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            do
            {
                QueueItem NewAction;
                lock (Actions)
                {
                    NewAction = Actions.Dequeue();
                }

                NewAction.Work();

                backgroundWorker1.ReportProgress(1, NewAction);

                lock (Actions)
                {
                    if (Actions.Count == 0)
                        break;
                }

                if (e.Cancel)
                    return;
                
            } while (true);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            
            QueueItem newAction = e.UserState as QueueItem;
            newAction.ProgressAction();

            toolStripStatusLabel.Text = "Rendering";
            toolStripProgressBar1.Value++;            
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;

            toolStripProgressBar1.Value = 0;
            toolStripProgressBar1.Maximum = 0;
            toolStripStatusLabel.Text = "";

            lock (Actions)
            {
                
            
                if (Actions.Count > 0)
                {
                    toolStripProgressBar1.Maximum = Actions.Count;
                    backgroundWorker1.RunWorkerAsync();
                }
            }
        }

        private void MDIParent_FormClosing(object sender, FormClosingEventArgs e)
        {
            Settings.Default.Save();
            if (backgroundWorker1.IsBusy)
            backgroundWorker1.CancelAsync();
        }

        private void toolStripButtonExportSingle_Click(object sender, EventArgs e)
        {
            var activeDocument = ActiveMdiChild as PageForm;
            if (activeDocument == null)
                return;

            FastExport(activeDocument, false);
           
            
        }

        private void FastExport(PageForm activeDocument, bool SilentSkip)
        {
            var newFilename = GetFastExportFileName(activeDocument);

            if (File.Exists(newFilename) && SilentSkip)
                return;
            
            activeDocument.SaveAs(newFilename);
        }

        private string GetFastExportFileName(PageForm activeDocument)
        {
            if (activeDocument == null)
                return null;

            var newDirectory = toolStripTextBoxFastExportDirectorz.Text;

            var newFilename = Path.Combine(newDirectory, activeDocument.PdfFileInfo.Name);
            return newFilename;
        }

        private void MDIParent_MdiChildActivate(object sender, EventArgs e)
        {
            var Filename = GetFastExportFileName(ActiveMdiChild as PageForm);


            toolStripStatusLabelOutputFileExists.Visible = Filename != null && File.Exists(Filename);
           // toolStripButtonExportSingle.Enabled = Filename != null && !File.Exists(Filename);
            
        }

        private void toolStripButtonExportAll_Click(object sender, EventArgs e)
        {
            foreach (var activeDocument in MdiChildren.OfType<PageForm>())
            {
                FastExport(activeDocument, false);
            }
        }

        private void indexToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://sourceforge.net/p/pdfebookcutter/home/Home/");
        }

        private void toolStripTextBoxFastExportDirectorz_Click(object sender, EventArgs e)
        {
          
        }

        private void toolStripTextBoxFastExportDirectorz_TextChanged(object sender, EventArgs e)
        {
            MDIParent_MdiChildActivate(sender, e);
            Settings.Default.LastExportDir = toolStripTextBoxFastExportDirectorz.Text;
            Settings.Default.Save();
        }

     
    }
}
